<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="icon" type="image/png" sizes="16x16" href="https://gitee.com/reku1997/reku1997/raw/master/reku.ico">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"reku1997.gitee.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"flat"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"appID":"AW5K8S9IEE","apiKey":"d7e666d597854738d2fb31ecaa989aa5","indexName":"dev_reku1997","hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="在几个月前，试图开了一下MIT 6.828的坑，但是因为各种原因，只做了lab1就搁置了。前几天突然在知乎上看到了二十八画生征友：一起来通关6.S081&#x2F;6.828吧~，发现这个MIT 6.S081是MIT 6.828的简化版，而且梯度更加的平滑。">
<meta property="og:type" content="article">
<meta property="og:title" content="MIT-6.S081 2020">
<meta property="og:url" content="https://reku1997.gitee.io/2020/10/13/mit-os/index.html">
<meta property="og:site_name" content="Reku">
<meta property="og:description" content="在几个月前，试图开了一下MIT 6.828的坑，但是因为各种原因，只做了lab1就搁置了。前几天突然在知乎上看到了二十八画生征友：一起来通关6.S081&#x2F;6.828吧~，发现这个MIT 6.S081是MIT 6.828的简化版，而且梯度更加的平滑。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://reku1997.gitee.io/2020/10/13/mit-os/1.PNG">
<meta property="og:image" content="https://reku1997.gitee.io/2020/10/13/mit-os/2-1.PNG">
<meta property="og:image" content="https://reku1997.gitee.io/2020/10/13/mit-os/3-1.PNG">
<meta property="og:image" content="https://reku1997.gitee.io/2020/10/13/mit-os/5-1.PNG">
<meta property="og:image" content="https://reku1997.gitee.io/2020/10/13/mit-os/5-2.PNG">
<meta property="og:image" content="https://reku1997.gitee.io/2020/10/13/mit-os/5-3.PNG">
<meta property="article:published_time" content="2020-10-13T07:17:57.000Z">
<meta property="article:modified_time" content="2021-12-17T15:26:22.801Z">
<meta property="article:author" content="Reku">
<meta property="article:tag" content="OS">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://reku1997.gitee.io/2020/10/13/mit-os/1.PNG">

<link rel="canonical" href="https://reku1997.gitee.io/2020/10/13/mit-os/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-cn'
  };
</script>

  <title>MIT-6.S081 2020 | Reku</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="Reku" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Reku</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>Home</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>About</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>Tags</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>Archives</a>

  </li>
        <li class="menu-item menu-item-sitemap">

    <a href="/sitemap.xml" rel="section"><i class="fa fa-fw fa-sitemap"></i>Sitemap</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>Search
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container"></div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="algolia-results">
  <div id="algolia-stats"></div>
  <div id="algolia-hits"></div>
  <div id="algolia-pagination" class="algolia-pagination"></div>
</div>

      
    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-cn">
    <link itemprop="mainEntityOfPage" href="https://reku1997.gitee.io/2020/10/13/mit-os/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="Reku">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Reku">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          MIT-6.S081 2020
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2020-10-13 15:17:57" itemprop="dateCreated datePublished" datetime="2020-10-13T15:17:57+08:00">2020-10-13</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">Edited on</span>
                <time title="Modified: 2021-12-17 23:26:22" itemprop="dateModified" datetime="2021-12-17T23:26:22+08:00">2021-12-17</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">In</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/" itemprop="url" rel="index"><span itemprop="name">操作系统</span></a>
                </span>
            </span>

          
            <span id="/2020/10/13/mit-os/" class="post-meta-item leancloud_visitors" data-flag-title="MIT-6.S081 2020" title="Views">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">Views: </span>
              <span class="leancloud-visitors-count"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="fa fa-comment-o"></i>
      </span>
      <span class="post-meta-item-text">Valine: </span>
    
    <a title="valine" href="/2020/10/13/mit-os/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2020/10/13/mit-os/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>在几个月前，试图开了一下MIT 6.828的坑，但是因为各种原因，只做了lab1就搁置了。前几天突然在知乎上看到了<a target="_blank" rel="noopener" href="https://zhuanlan.zhihu.com/p/251366985">二十八画生征友：一起来通关6.S081/6.828吧~</a>，发现这个MIT 6.S081是MIT 6.828的简化版，而且梯度更加的平滑。 <span id="more"></span> 之前的一段时间都因为各种事情，忙的飞起。最近正好有一段空闲时间，希望可以在一个月内通关MIT 6.S081。</p>
<p>一个比较好的<a target="_blank" rel="noopener" href="https://mit-public-courses-cn-translatio.gitbook.io/mit6-s081/">参考资料</a>。</p>
<p>首先按照<a target="_blank" rel="noopener" href="https://pdos.csail.mit.edu/6.828/2020/tools.html">tools</a>配环境，因为我用的是Ubuntu 18的虚拟机，所以需要自己手动去编译riscv-gnu-toolchain，编译的过程其实非常简单，但是下载的过程非常痛苦。这边有个<a target="_blank" rel="noopener" href="https://blog.csdn.net/zhayujie5200/article/details/106374189/">老哥</a>直接把riscv-gnu-toolchain放到百度云盘上了，这样下载就会快很多而且不容易中断。</p>
<h1 id="lab-1-utilities">Lab-1 Utilities</h1>
<p>Lab1其实就是实现一些shell指令，做实验前一定要把<a target="_blank" rel="noopener" href="https://pdos.csail.mit.edu/6.828/2020/xv6/book-riscv-rev1.pdf">xv6 book</a>的第一章通读一遍，<strong>非常关键！！！</strong></p>
<h2 id="sleep-pingpong">sleep &amp; pingpong</h2>
<p>相对简单，略过。这个pingpong我是用两个pipe从两个方向传输的。</p>
<h2 id="primes">primes</h2>
<p>一个非常风骚的多进程筛法。主要流程如下图：</p>
<p><img src="/2020/10/13/mit-os/1.PNG"></p>
<p>其实就是每个素数开一个进程，多个进程形成一个pipeline。按顺序输入数字，如果一个数被前面所有进程漏掉，那他显然是一个素数，就再开一个进程进入pipeline。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&quot;kernel/types.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&quot;kernel/stat.h&quot;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&quot;user/user.h&quot;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span> p[<span class="number">36</span>][<span class="number">2</span>];</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">prime_fork</span><span class="params">(<span class="keyword">int</span> last, <span class="keyword">int</span> from)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (fork() == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">int</span> prime, now;</span><br><span class="line">        now = <span class="number">-1</span>; prime = <span class="number">-1</span>;</span><br><span class="line">        <span class="keyword">if</span> (last != <span class="number">-1</span>) &#123;</span><br><span class="line">            close(p[last][<span class="number">0</span>]);</span><br><span class="line">        &#125;</span><br><span class="line">        close(p[from][<span class="number">1</span>]);</span><br><span class="line">        <span class="keyword">while</span> (read(p[from][<span class="number">0</span>], &amp;now, <span class="number">4</span>)) &#123;</span><br><span class="line">            <span class="keyword">if</span> (prime == <span class="number">-1</span>) &#123;</span><br><span class="line">                prime = now;</span><br><span class="line">                pipe(p[prime]);</span><br><span class="line">                prime_fork(from, prime);</span><br><span class="line">                close(p[prime][<span class="number">0</span>]);</span><br><span class="line">                <span class="built_in">printf</span>(<span class="string">&quot;prime %d\n&quot;</span>, prime);</span><br><span class="line">                <span class="keyword">continue</span>;</span><br><span class="line">            &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                <span class="keyword">if</span> (now % prime == <span class="number">0</span>) &#123;</span><br><span class="line">                    <span class="keyword">continue</span>;</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    write(p[prime][<span class="number">1</span>], &amp;now, <span class="number">4</span>);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (prime != <span class="number">-1</span>) &#123;</span><br><span class="line">            close(p[prime][<span class="number">1</span>]);</span><br><span class="line">            wait(<span class="number">0</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">exit</span>(<span class="number">0</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    pipe(p[<span class="number">1</span>]);</span><br><span class="line">    prime_fork(<span class="number">-1</span>, <span class="number">1</span>);</span><br><span class="line">    close(p[<span class="number">1</span>][<span class="number">0</span>]);</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">2</span>; i &lt;= <span class="number">35</span>; i++) &#123;</span><br><span class="line">        write(p[<span class="number">1</span>][<span class="number">1</span>], &amp;i, <span class="number">4</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    close(p[<span class="number">1</span>][<span class="number">1</span>]);</span><br><span class="line">    wait(<span class="number">0</span>);</span><br><span class="line">    <span class="built_in">exit</span>(<span class="number">0</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我直接暴力的用了一个p数组，代表每个进程向下传输所需要的pipe。一个素数的进程的pipe就直接使用p[素数]的数组就好了。因为fd空间不够35以内的素数开满，所以要管理fd，这个地方要小心处理，我因为close了一些回收过的fd错了好几次。</p>
<p>一个值得注意的地方是read前的close(p[from][1])，这个bug我也卡了一小会儿，这里直接引用xv6 book中的原文：</p>
<blockquote>
<p>If no data is available, a read on a pipe waits for either data to be written or for all file descriptors referring to the write end to be closed.</p>
</blockquote>
<p>没错，是all file descriptors都要close才行，不然read就会一直挂在那里，导致死循环。</p>
<h2 id="find">find</h2>
<p>这个本身其实挺复杂的，幸好ls指令已经写好了，所以直接抄就完事儿了。</p>
<h2 id="xargs">xargs</h2>
<p>这个理论上其实很简单，就是解析标准读入进来的字符串，先按照'\n' split一下，再按照' ' split一下，最后拼成argv就好了。但是有个地方非常坑爹，我最开始的时候，从标准读入读字符串，简单写成了这样：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">buf_size = read(0, buf, (sizeof buf))</span><br><span class="line">do something with buf...</span><br></pre></td></tr></table></figure>
<p>这么写完之后，make grade大概五次会错一次，非常诡异。一般来说这种情况都是多进程出了问题，这时再掏出xv6 book的原文：</p>
<blockquote>
<p>The child process creates a pipe to connect the left end of the pipeline with the right end. Then it calls fork and runcmd for the left end of the pipeline and fork and runcmd for the right end, and waits for both to finish.</p>
</blockquote>
<p>一个pipe的左右指令是多进程，所以当左边指令输出，右边指令输入的时候，应该写成阻塞式：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span> ((buf_size = read(<span class="number">0</span>, buf + offset, (<span class="keyword">sizeof</span> buf) - offset)) != <span class="number">0</span>) &#123;</span><br><span class="line">    offset += buf_size;</span><br><span class="line">&#125;</span><br><span class="line">buf_size = offset;</span><br></pre></td></tr></table></figure>
<p>我跑了十次，全都通过了testcase。</p>
<h1 id="lab-2-system-calls">Lab-2 System calls</h1>
<p>这次实验是实现两个系统调用trace和sysinfo，感觉在实现上没什么好说的，两个任务都比较简单。这里想重点总结一下整个xv6的boot和system call的流程。</p>
<p>首先讲讲boot的整个流程。我们的整个实验环境是搭建在RISC-V上面的，在RISC-V中，CPU运行的指令分成三种模式：machine mode, supervisor mode和user mode。最开始的时候，CPU是处于machine mode的。开机后，CPU运行boot loader中的指令，把整个kernel都给load进来。然后进入entry.S：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">_entry:</span><br><span class="line">	# set up a stack for C.</span><br><span class="line">        # stack0 is declared in start.c,</span><br><span class="line">        # with a 4096-byte stack per CPU.</span><br><span class="line">        # sp = stack0 + (hartid * 4096)</span><br><span class="line">        la sp, stack0</span><br><span class="line">        li a0, 1024*4</span><br><span class="line">	csrr a1, mhartid</span><br><span class="line">        addi a1, a1, 1</span><br><span class="line">        mul a0, a0, a1</span><br><span class="line">        add sp, sp, a0</span><br><span class="line">	# jump to start() in start.c</span><br><span class="line">        call start</span><br></pre></td></tr></table></figure>
<p>entry.S的任务就是初始化stack，然后开始call start.c:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span></span></span><br><span class="line"><span class="function"><span class="title">start</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="comment">// set M Previous Privilege mode to Supervisor, for mret.</span></span><br><span class="line">  <span class="keyword">unsigned</span> <span class="keyword">long</span> x = r_mstatus();</span><br><span class="line">  x &amp;= ~MSTATUS_MPP_MASK;</span><br><span class="line">  x |= MSTATUS_MPP_S;</span><br><span class="line">  w_mstatus(x);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// set M Exception Program Counter to main, for mret.</span></span><br><span class="line">  <span class="comment">// requires gcc -mcmodel=medany</span></span><br><span class="line">  w_mepc((uint64)main);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// disable paging for now.</span></span><br><span class="line">  w_satp(<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// delegate all interrupts and exceptions to supervisor mode.</span></span><br><span class="line">  w_medeleg(<span class="number">0xffff</span>);</span><br><span class="line">  w_mideleg(<span class="number">0xffff</span>);</span><br><span class="line">  w_sie(r_sie() | SIE_SEIE | SIE_STIE | SIE_SSIE);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// ask for clock interrupts.</span></span><br><span class="line">  timerinit();</span><br><span class="line"></span><br><span class="line">  <span class="comment">// keep each CPU&#x27;s hartid in its tp register, for cpuid().</span></span><br><span class="line">  <span class="keyword">int</span> id = r_mhartid();</span><br><span class="line">  w_tp(id);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// switch to supervisor mode and jump to main().</span></span><br><span class="line">  <span class="function"><span class="keyword">asm</span> <span class="title">volatile</span><span class="params">(<span class="string">&quot;mret&quot;</span>)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在RISC-V中，mret、sret和uret分别用于从machine、supervisor和user模式中的trap返回。这里调用的是mret，其实就是从machine mode返回到supervisor mode。</p>
<p>在main.c中，userinit函数首先allocproc()出来第一个用户进程，然后执行initcode.S中的指令，这个指令其实就是调用SYS_exec执行init.c：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">.globl start</span><br><span class="line">start:</span><br><span class="line">        la a0, init</span><br><span class="line">        la a1, argv</span><br><span class="line">        li a7, SYS_exec</span><br><span class="line">        ecall</span><br><span class="line"></span><br><span class="line"># for(;;) exit();</span><br><span class="line">exit:</span><br><span class="line">        li a7, SYS_exit</span><br><span class="line">        ecall</span><br><span class="line">        jal exit</span><br><span class="line"></span><br><span class="line"># char init[] = &quot;/init\0&quot;;</span><br><span class="line">init:</span><br><span class="line">  .string &quot;/init\0&quot;</span><br><span class="line"></span><br><span class="line"># char *argv[] = &#123; init, 0 &#125;;</span><br><span class="line">.p2align 2</span><br><span class="line">argv:</span><br><span class="line">  .long init</span><br><span class="line">  .long 0</span><br></pre></td></tr></table></figure>
<p>在init.c中，系统生成一个名为"console"的device，并重载标准输出跟标准错误输出到这个device上，之后启动sh.c，shell启动，正式进入操作系统。</p>
<p>然后再讲讲整个system call的流程。这里我们可以用作业中的Sysinfo作为例子。</p>
<p>Sysinfo的功能是统计一下当前系统的剩余内存和已经使用的进程数量，并把这两个参数组装成一个结构体，传回给用户。这里就要分为三步，首先在user mode进行system call，进入supervisor mode，然后统计两个信息，最后system call return需要的信息回来。</p>
<p>我们要在user mode中调用这个sysinfo函数，但是因为这是一个系统调用，肯定不能在user mode里面实现，所以需要一个user mode的函数与supervisor mode的system call的绑定。具体到代码中，其实就是user/usys.pl中会有个entry("sysinfo")，这个语句会生成一段汇编代码：</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">sysinfo:</span><br><span class="line"> li a7, SYS_sysinfo</span><br><span class="line"> ecall</span><br><span class="line"> ret</span><br></pre></td></tr></table></figure>
<p>这个ecall指令会让我们进入supervisor mode并运行SYS_sysinfo函数。那么问题来了，我们看到系统调用的参数都是(void)的，并且我们当前user mode的各种寄存器要怎么保存呢？要解决这个问题，首先要知道ecall指令到底干了什么，在xv6 book中，是这样说的：</p>
<blockquote>
<p>The ecall instruction traps into the kernel and executes uservec, usertrap, and then syscall, as we saw above.</p>
</blockquote>
<p>uservec是一段汇编，主要是保护当前的user mode现场，将user进程中的寄存器数据放到TRAPFRAME中，同时加载kernel的页表。然后调用trap.c/usertrap()。</p>
<p>在trap.c/usertrap()会进入syscall(void)函数，syscall(void)会根据a7寄存器中的值调用对应的system call，system call参数的传递通过TRAPFRAME中的a0-a5寄存器，运行过后的返回值放到p-&gt;trapframe-&gt;a0寄存器中。</p>
<p>然后调用userret，也是一段汇编代码。userret会恢复user mode的页表，并且从TRAPFRAME中恢复过去的寄存器，这样就完成了一次系统调用。但是我们发现，system call并没有传递任何值给user mode，其实system call的返回值要通过copyout函数，直接写入该进程在user mode能使用的地址中。</p>
<h1 id="lab-3-page-tables">Lab-3 Page tables</h1>
<p>这个实验相对复杂，要比较清晰的理解页表才能顺利的完成。</p>
<p>首先，我们要了解页表是个什么东西。其实页表就是个(key, value)的pair集合，key是虚拟地址，value是物理地址，在程序使用的地址跟计算机实际运行的内存地址之间产生一层隔离关系。</p>
<p>这种隔离关系的好处是，不同进程之间无法直接访问对方的变量，恶意程序也无法破坏整个操作系统，只能破坏自己的进程。</p>
<p>其次，还可以使得物理上不连续的、不从0开始的物理地址变成连续的、从0开始的虚拟地址，方便内核做统一的内存管理，而不是每个进程自己乱管理。</p>
<h2 id="print-a-page-table">Print a page table</h2>
<p><img src="/2020/10/13/mit-os/2-1.PNG"></p>
<p>完成打印页表的任务，只需要理解这个三级页表的架构就好了。从图片可以轻松了解这个数据结构，但是作为一个kv系统，为什么要这么设计呢？</p>
<p>其实很简单，如果页表只有一级，那就是空间换时间，一个巨大的桶存着页表。如果页表级数特别多，那访问时间就会很慢。三级页表就是个设计上的trade-off，而且这么设计，每一级页表就是一个page的大小，我觉得代码会更加规整。</p>
<p>判断一个页表的内容是否合法，其实就是对应一些掩码的位置，核心逻辑如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span></span><br><span class="line">_vmprint(<span class="keyword">pagetable_t</span> pagetable, <span class="keyword">int</span> level)</span><br><span class="line">&#123;</span><br><span class="line">  <span class="comment">// there are 2^9 = 512 PTEs in a page table.</span></span><br><span class="line">  <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">512</span>; i++) &#123;</span><br><span class="line">    <span class="keyword">pte_t</span> pte = pagetable[i];</span><br><span class="line">    <span class="keyword">if</span> (pte &amp; PTE_V) &#123;</span><br><span class="line">        uint64 child = PTE2PA(pte);</span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> j = <span class="number">0</span>; j &lt; level; j++) &#123;</span><br><span class="line">            <span class="built_in">printf</span>(<span class="string">&quot;..&quot;</span>);</span><br><span class="line">            <span class="keyword">if</span> (j + <span class="number">1</span> != level) <span class="built_in">printf</span>(<span class="string">&quot; &quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;%d: pte %p pa %p\n&quot;</span>, i, pte, child);</span><br><span class="line">        <span class="keyword">if</span> ((pte &amp; (PTE_R|PTE_W|PTE_X)) == <span class="number">0</span>) &#123;</span><br><span class="line">            _vmprint((<span class="keyword">pagetable_t</span>)child, level + <span class="number">1</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="a-kernel-page-table-per-process">A kernel page table per process</h2>
<p>这个环节又涉及到一个新的问题：用户级页表和内核级页表。</p>
<p>在上个环节我们已经知道，页表的主要功能是为了控制访问权限。那么理论上来说，每个用户级进程都要有自己的页表，从而只能访问自己的地址，不能访问别人的地址。内核既然是随便访问，那么用一个固定不变的内核页表就好了。所以在用户级进程与系统调用之间涉及到一个页表切换的问题。</p>
<p>kernel page table per process要求我们实现一个新功能，内核页表不再是全局的，而是每个进程独立的。这个任务分成两步：建立每个进程自己的内核页表、实现页表切换。</p>
<p>首先看一下内核页表在哪里进行了改动，我只发现了两个地方，一个是kvminit()，将低地址的IO device和trampoline映射到页表中。第二个是procinit()，这里声明了进程池中每个进程的栈空间，并跟内核页表进行绑定，方便内核从每个进程的栈中获取参数之类的。</p>
<p>那这个建立每个进程自己的内核页表就很简单的，先把kvminit()里面的东西都映射到每个进程的内核页表中，再绑定自己进程的栈就可以了。</p>
<p>实现页表切换分为两步，将页表写入satp寄存器，然后用sfence.vma刷新TLB，所以页表命中是完全靠硬件，页表缺失会引起中断，需要操作系统跟硬件的配合。在scheduler()中就可以进行页表的切换，需要注意的是，进程的内核部分运行结束后要立刻把页表切换成全局的内核页表。</p>
<h2 id="simplify-copyincopyinstr">Simplify copyin/copyinstr</h2>
<p>经过上一轮的准备之后，我们可以简化copyin/copyinstr的流程。copyin是一个系统调用，要把进程中内存的一些东西copy到内核中，这里的问题在于，系统调用传入的地址是一个虚拟地址，在没有进程中的用户页表的情况下，我们无从得知该虚拟地址对应的物理地址的位置。所以在xv6中，copyin的函数签名为：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">copyin</span><span class="params">(<span class="keyword">pagetable_t</span> pagetable, <span class="keyword">char</span> *dst, uint64 srcva, uint64 len)</span></span></span><br></pre></td></tr></table></figure>
<p>这里问题的关键是，因为内核页表是全局的，我们无法修改内核页表，让硬件帮助我们完成虚拟地址到物理地址的转换，所以要先进行一步软件层面的转换，然后通过内核页表的直接映射的性质去完成系统调用。当然，我们在上一个环节实现了每个进程自己维护的内核页表，所以我们可以将虚拟地址的映射加入到自己维护的内核页表中。</p>
<p>这里为了保持一致性，要小心的修改，在fork(), exec()和sbrk()的函数中，都有对虚拟地址映射的修改，主要增加或是改变对应内存大小。</p>
<p>这里其实有个问题，就是内核页表是采用直接映射的方式。也就是在映射用户的虚拟地址之前，低位其实已经映射一些内容了，这就会导致remap。一方面要调整我们的函数去忽略remap，另一方面lab指导中告诉我们，PLIC寄存器之前的空间都可以随便映射。</p>
<h1 id="lab-4-traps">Lab-4 Traps</h1>
<p>该实验系统的总结了trap的流程，其中大致的流程我们在上一篇文章lab2中都已经叙述过了，通过lab4，我们会对整个流程理解的更加深刻。</p>
<p>trap来自三种情况：syscall对ecall的调用、程序运行的错误、设备中断（比如时钟）。当中断发生时，我们会自动运行一段运行好的程序，当然，kernel中断跟user中断运行的程序应该是不同的，所以要用一个寄存器储存这段程序的位置。user中断的过程会相对复杂，因为user process会发生各种事情，所以我们就从user中断讲起。user中断运行的位置就是trampoline中的uservec。</p>
<p>uservec的功能我们lab2中已经分析过了，主要是切换页表跟保护现场两个功能。因为要使得切换页表后，trampoline中的程序在用户态和内核态都能运行，所以trampoline在内核页表和用户页表中要完全相同。</p>
<p>之后在usertrap中判断trap的类型，systemcall就去准备systemcall，时钟中断就去修改process的状态，错误就直接kill整个process，之后再调用userret将之前保护的现场还原回去以及将页表改回用户页表。</p>
<p>内核的trap跟用户的trap原理相似，但是一个很重要也很繁琐的细节就是，当user trap进入内核态的时候，内核也有可能继续trap。这就要求我们在进入user trap的时候，要准备好所有kernel trap可能用到的东西，以及保存kernel trap可能破坏的位置，方便kernel trap结束后进行恢复。</p>
<h2 id="risc-v-assembly">RISC-V assembly</h2>
<p>作业让我们熟悉一下RISC-V，群里大佬们推荐了一本包云岗翻译的RISC-V的教材，可以用来查询。</p>
<p>询问了一些简单的RISC-V的问题，但是要注意，他的编译器是默认开优化的，比如第一问：</p>
<blockquote>
<p>Which registers contain arguments to functions? For example, which register holds 13 in main's call to printf?</p>
</blockquote>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">  <span class="built_in">printf</span>(<span class="string">&quot;%d %d\n&quot;</span>, f(<span class="number">8</span>)+<span class="number">1</span>, <span class="number">13</span>);</span><br><span class="line"><span class="number">24</span>:	<span class="number">4635</span>                	li	a2,<span class="number">13</span></span><br><span class="line"><span class="number">26</span>:	<span class="number">45b</span>1                	li	a1,<span class="number">12</span></span><br><span class="line"><span class="number">28</span>:	<span class="number">00000517</span>          	auipc	a0,<span class="number">0x0</span></span><br><span class="line"><span class="number">2</span>c:	<span class="number">7b</span>050513          	addi	a0,a0,<span class="number">1968</span> # <span class="number">7</span>d8 &lt;<span class="built_in">malloc</span></span><br></pre></td></tr></table></figure>
<p>看指令，这个13可以理解是什么，但是这个12是哪来的。再一看f跟g函数，估计是太简单被直接常量折叠了，那我们就把编译选项加上-O0再来一遍。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">printf</span>(<span class="string">&quot;%d %d\n&quot;</span>, f(<span class="number">8</span>)+<span class="number">1</span>, <span class="number">13</span>);</span><br><span class="line"><span class="number">4</span>c:	<span class="number">4521</span>                	li	a0,<span class="number">8</span></span><br><span class="line"><span class="number">4</span>e:	<span class="number">00000097</span>          	auipc	ra,<span class="number">0x0</span></span><br><span class="line"><span class="number">52</span>:	fce080e7          	jalr	<span class="number">-50</span>(ra) # <span class="number">1</span>c &lt;f&gt;</span><br><span class="line"><span class="number">56</span>:	<span class="number">87</span>aa                	mv	a5,a0</span><br><span class="line"><span class="number">58</span>:	<span class="number">2785</span>                	addiw	a5,a5,<span class="number">1</span></span><br><span class="line"><span class="number">5</span>a:	<span class="number">2781</span>                	sext.w	a5,a5</span><br><span class="line"><span class="number">5</span>c:	<span class="number">4635</span>                	li	a2,<span class="number">13</span></span><br><span class="line"><span class="number">5</span>e:	<span class="number">85b</span>e                	mv	a1,a5</span><br><span class="line"><span class="number">60</span>:	<span class="number">00001517</span>          	auipc	a0,<span class="number">0x1</span></span><br><span class="line"><span class="number">64</span>:	d0850513          	addi	a0,a0,<span class="number">-760</span> # d68 &lt;<span class="built_in">malloc</span>+<span class="number">0x13e</span>&gt;</span><br><span class="line"><span class="number">68</span>:	<span class="number">00001097</span>          	auipc	ra,<span class="number">0x1</span></span><br><span class="line"><span class="number">6</span>c:	<span class="number">9</span>d0080e7          	jalr	<span class="number">-1584</span>(ra) # a38 &lt;<span class="built_in">printf</span>&gt;</span><br></pre></td></tr></table></figure>
<p>可以比较清楚的看出来，第一个f(8)+1在a1寄存器中，第二个13在a2寄存器中。</p>
<h2 id="backtrace">Backtrace</h2>
<p>这个任务就是输出调用栈信息，这些任务都存在stack中，stack结构在slide中可以看到：</p>
<p><img src="/2020/10/13/mit-os/3-1.PNG"></p>
<p>其中初始的frame-pointer值，实验指导已经给出了代码。那问题就在于什么时候停止往前回溯。其实只要frame-pointer等于PGROUNDUP(fp)就可以跳出循环了。因为最浅层的那个调用既没有frame-pointer，也没有return address。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span></span></span><br><span class="line"><span class="function"><span class="title">backtrace</span><span class="params">(<span class="keyword">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="built_in">printf</span>(<span class="string">&quot;backtrace:\n&quot;</span>);</span><br><span class="line">  uint64 fp = r_fp();</span><br><span class="line">  uint64 upper_bound = PGROUNDUP(fp);</span><br><span class="line">  uint64 ra;</span><br><span class="line">  <span class="keyword">while</span> (<span class="number">1</span>)</span><br><span class="line">  &#123;</span><br><span class="line">    ra = *((uint64*)(fp - <span class="number">8</span>));</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;%p\n&quot;</span>, ra);</span><br><span class="line">    fp = *((uint64*)(fp - <span class="number">16</span>));</span><br><span class="line">    <span class="keyword">if</span> (fp == upper_bound) <span class="keyword">break</span>;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="alarm">Alarm</h2>
<p>这个实验难度较大，让我们实现一个syscall，可以监控cpu在该进程上的运行时间。单独监控运行时间其实比较简单，大致思路就是在process里面加个变量，当产生时间片中断时，就把这个变量++，然后输出。但问题是，实验让我们完成的函数是sigalarm(int ticks, void (*handler)())这种形式的。每次经过ticks时间片，就调用一下handler函数。</p>
<p>我们根据实验材料中的提示，可以简单得到这样一个思路：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// give up the CPU if this is a timer interrupt.</span></span><br><span class="line"><span class="keyword">if</span>(which_dev == <span class="number">2</span>)</span><br><span class="line">&#123;</span><br><span class="line">p-&gt;timer ++;</span><br><span class="line"><span class="keyword">if</span> (p-&gt;timer == p-&gt;ticks) &#123;</span><br><span class="line">    p-&gt;timer = <span class="number">0</span>;</span><br><span class="line">    p-&gt;trapframe-&gt;epc = (uint64)p-&gt;handler;</span><br><span class="line">&#125;</span><br><span class="line">yield();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样当调用usertrapret()之后，会自动运行handler位置的程序。但是当我们运行test程序之后，发现第一次监控输出之后，后面的程序会发生混乱。</p>
<p>简单分析一下，可以发现，我们回到handler之后，并没有再回到原本process运行的位置。这样就会产生补救的思路，先把trapframe存起来，然后当handler运行结束后，通过另一个系统调用，将trapframe恢复：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">p-&gt;timer ++;</span><br><span class="line"><span class="keyword">if</span> (p-&gt;timer == p-&gt;ticks) &#123;</span><br><span class="line">    p-&gt;timer = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">if</span> (p-&gt;ishandle == <span class="number">0</span>)</span><br><span class="line">    &#123;</span><br><span class="line">        p-&gt;ishandle = <span class="number">1</span>;</span><br><span class="line">        memmove(p-&gt;dump_trapframe, p-&gt;trapframe, <span class="keyword">sizeof</span>(struct trapframe));</span><br><span class="line">        p-&gt;trapframe-&gt;epc = (uint64)p-&gt;handler;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function">uint64</span></span><br><span class="line"><span class="function"><span class="title">sys_sigreturn</span><span class="params">(<span class="keyword">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">proc</span> *<span class="title">p</span> =</span> myproc();</span><br><span class="line">  p-&gt;ishandle = <span class="number">0</span>;</span><br><span class="line">  memmove(p-&gt;trapframe, p-&gt;dump_trapframe, <span class="keyword">sizeof</span>(struct trapframe));</span><br><span class="line">  <span class="keyword">return</span> <span class="number">0</span>;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>因为有个slow_handler()测试点，暗示我们handler运行的过程中，计时功能应该关闭，所以我们要加一个p-&gt;ishandle变量来把门。</p>
<h1 id="lab-5-lazy-page-allocation">Lab-5 Lazy Page Allocation</h1>
<p>该实验主要是对sbrk的修改，就是当一个process要求操作系统分配更多内存给他的时候，并不直接进行分配，而是当process真的访问到该内存的时候，再进行分配，整个过程都是由缺页中断进行驱动的。</p>
<h2 id="eliminate-allocation-from-sbrk">Eliminate allocation from sbrk()</h2>
<p>非常简单，只要修改p-&gt;sz就行了，不需要进行任何其他操作。</p>
<h2 id="lazy-allocation">Lazy allocation</h2>
<p>通过这个case其实也非常简单，我感觉怎么写都能过，我在写这个的时候错了好几个地方，都成功通过echo hi了。</p>
<p>原理也比较简单，就是在缺页中断的时候调用一下mappages。</p>
<h2 id="lazytests-and-usertests">Lazytests and Usertests</h2>
<p>这个任务要求我们通过修改上一个任务的代码，从而通过两个非常复杂的程序。这里我遇到了两个非常坑爹的地方。</p>
<p>首先是lazytests里面的oom，我总是在oom之前就发生p-&gt;sz整数溢出。发现p-&gt;sz是uint64类型的，理论不应该溢出才是。</p>
<p>观察一下原有的sbrk的写法：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> addr;</span><br><span class="line"><span class="keyword">int</span> n;</span><br><span class="line"><span class="keyword">if</span>(argint(<span class="number">0</span>, &amp;n) &lt; <span class="number">0</span>)</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">addr = myproc()-&gt;sz;</span><br><span class="line"><span class="keyword">if</span>(growproc(n) &lt; <span class="number">0</span>)</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line"><span class="keyword">return</span> addr;</span><br></pre></td></tr></table></figure>
<p>这里，大部分人第一次都会去用myproc()-&gt;sz=addr+n来修改sbrk，然而这个位置会导致整形溢出，也就是他默认的数据类型会溢出，非常坑爹！</p>
<p>还有一个地方，更加恶心。就是usertests的sbrkargs，我跑了所有其他case都能通过，就这个case无法通过。</p>
<p>经过细致的排查，发现sbrkarg的特殊之处在于，他是在copyin这个函数里面软查找页表的时候产生缺页的，不会产生缺页中断，但是会导致写入失败。所以要在walkaddr里面也处理一下lazy alloc的情况。</p>
<p>也就是说，不是所有缺页都是通过缺页中断驱动的，真是令人作呕的设计啊...</p>
<h1 id="lab-6-copy-on-write-fork-for-xv6">Lab-6 Copy-on-Write Fork for xv6</h1>
<p>下面是页表的最后一个实验，实现xv6 fork的COW机制。</p>
<p>超级恶心，写了我整整一天，各种坑点非常多，而且难以debug。这里建议先从给页表进行引用计数下手，一个显而易见的思路是，将kmem改成如下这样：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">struct</span> &#123;</span></span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">spinlock</span> <span class="title">lock</span>;</span></span><br><span class="line">  <span class="keyword">int</span> ref_cnt[PHYSTOP / PGSIZE];</span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">run</span> *<span class="title">freelist</span>;</span></span><br><span class="line">&#125; kmem;</span><br></pre></td></tr></table></figure>
<p>可能有人会疑惑这个引用数组到底开到了RAM的什么地方？其实这个数组会在link的时候开到RAM上，并通过linker算出extern char end[]的位置，所以只要不是太大，并不会影响到整个程序的运行。这个其实就相当于一个无碰撞的hash表，如果想节省内存，还可以搞点复杂的hash表动态扩容啥的，然而嫌麻烦，就没有搞。然后这个freelist记录的就是所有引用计数为0的page了。</p>
<p>后面就需要注意uvmcopy以及缺页中断的情况了。在实验的提示中，他说可以利用RISC-V的RSW位，然而我并没有用这个东西，最后也成功通过了所有的case，核心函数如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span></span></span><br><span class="line"><span class="function"><span class="title">fix_cow</span><span class="params">(<span class="keyword">pagetable_t</span> pagetable, uint64 va)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  uint64 pa;</span><br><span class="line">  <span class="keyword">if</span> ((pa = walkaddr(pagetable, va)) == <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">char</span> *mem;</span><br><span class="line">  <span class="keyword">if</span> ((mem = kalloc()) == <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  memmove(mem, (<span class="keyword">char</span>*)pa, PGSIZE);</span><br><span class="line">  uvmunmap(pagetable, va, <span class="number">1</span>, <span class="number">1</span>);</span><br><span class="line">  <span class="keyword">if</span>(mappages(pagetable, va, PGSIZE, (uint64)mem, PTE_W|PTE_X|PTE_R|PTE_U) != <span class="number">0</span>)&#123;</span><br><span class="line">    kfree(mem);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>我最开始的时候把前两个if写反了，导致countfree怎么都通过不了，非常坚硬，研究了半天。要小心谨慎的维护page，基本所有错误都是page的alloc和free导致的。</p>
<h1 id="lab-7-multithreading">Lab-7 Multithreading</h1>
<p>教材这一部分有点难读，大量内容都在解释有关xv6内部内核线程同步的代码，有些烧脑。幸好作业部分非常简单，完成的非常顺利。</p>
<h2 id="uthread-switching-between-threads">Uthread: switching between threads</h2>
<p>这个任务是给xv6添加用户线程，其实跟内核线程的添加方式几乎完全相同，因为没有让我们实现锁机制，所以整体的思路非常简单。</p>
<p>最核心的地方就是切换thread运行的context，这个地方采用跟内核线程一样的方式，只要保存返回地址、栈指针、callee-saved就可以了。</p>
<p>通过阅读xv6教材，我的理解是，其实内核没有进程的概念，只有用户有进程的概念。只是用户进程trap进入内核态之后，有个内核线程与该进程绑定而已。</p>
<h2 id="using-threads">Using threads</h2>
<p>这个任务也非常简单，给一个最简单的开散列hash表加锁，并稍微优化一下性能。</p>
<p>最简单的思路就是每个bucket都加个锁，恰好能达到要求的1.25x的加速：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">static</span> </span></span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">put</span><span class="params">(<span class="keyword">int</span> key, <span class="keyword">int</span> value)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="keyword">int</span> i = key % NBUCKET;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// is the key already present?</span></span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">entry</span> *<span class="title">e</span> =</span> <span class="number">0</span>;</span><br><span class="line">  pthread_mutex_lock(&amp;lock[i]);       <span class="comment">// acquire lock</span></span><br><span class="line">  <span class="keyword">for</span> (e = table[i]; e != <span class="number">0</span>; e = e-&gt;next) &#123;</span><br><span class="line">    <span class="keyword">if</span> (e-&gt;key == key)</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span>(e)&#123;</span><br><span class="line">    <span class="comment">// update the existing key.</span></span><br><span class="line">    e-&gt;value = value;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// the new is new.</span></span><br><span class="line">    insert(key, value, &amp;table[i], table[i]);</span><br><span class="line">  &#125;</span><br><span class="line">  pthread_mutex_unlock(&amp;lock[i]);     <span class="comment">// release lock</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="barrier">Barrier</h2>
<p>barrier指的就是所有线程都执行到此步之后，在进行后续的程序执行。实际上是对xv6的sleep和wakeup机制的复习。</p>
<p>整体思路也比较简单，只要加锁就好了：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span> </span></span><br><span class="line"><span class="function"><span class="title">barrier</span><span class="params">()</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  pthread_mutex_lock(&amp;bstate.barrier_mutex);</span><br><span class="line">  bstate.nthread ++;</span><br><span class="line">  <span class="keyword">if</span> (bstate.nthread != nthread) &#123;</span><br><span class="line">      pthread_cond_wait(&amp;bstate.barrier_cond, &amp;bstate.barrier_mutex);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      bstate.nthread = <span class="number">0</span>;</span><br><span class="line">      bstate.round ++;</span><br><span class="line">      pthread_cond_broadcast(&amp;bstate.barrier_cond);</span><br><span class="line">  &#125;</span><br><span class="line">  pthread_mutex_unlock(&amp;bstate.barrier_mutex);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="lab-8-locks">Lab-8 Locks</h1>
<p>教材中主要讲解了xv6系统中各种锁的设计理念。在xv6中，内部锁是由_sync_语句来保证原子性的，感觉这种思路确实相对比较简单。</p>
<p>因为CPU会进行乱序发射之类的指令顺序的优化，所以在很多情况下，需要显式的加上__sync_synchronize()，防止CPU进行跨越该语句的乱序发射。</p>
<p>两个任务具有一定的相似性，一个是优化buffer cache的锁，一个是优化kalloc的锁。我采用的方案也比较相似，在kalloc中，每个CPU弄一个独立的链表，在buffer cache中，每个blockbnum的hash值弄一个独立的链表。</p>
<p>在刚刚开始进行kalloc实验的时候，我走进了一个误区，以为freerange是在每个CPU上面执行的，这里保留一下学习群里的聊天记录，感谢群里的老哥们：</p>
<p><img src="/2020/10/13/mit-os/5-1.PNG"></p>
<h1 id="lab-9-file-system">Lab-9 File System</h1>
<p>感觉教材阅读起来比较困难，因为整个 File System 是分成 7 层层层抽象来构建的，我边参考代码边读了差不多三四遍，才完全把整个结构理解。整个层级图如下图所示：</p>
<p><img src="/2020/10/13/mit-os/5-2.PNG"></p>
<h2 id="large-files">Large files</h2>
<p>这个任务的难度不是太大，正常的文件 innode 结构是这样的：</p>
<p><img src="/2020/10/13/mit-os/5-3.PNG"></p>
<p>这样的二级结构使得每个文件只能支持 12+256 个 block，可以变成三级结构，使得整个文件能达到 11+256+256*256 个 block。只要小心的修改 itrunc 和 bmap 函数就可以了。</p>
<h2 id="symbolic-links">Symbolic links</h2>
<p>这个任务的难点在于要清晰的了解他想让你实现的 Symbolic links 行为到底是什么样子的。当 open 不带有 O_NOFOLLOW 标记时，需要一直向下找到 hard link 的位置。整个 symbolic link 的内容都要放在对应的 inode 上面，实际上只需要自己去将文件路径和路径长度保存在 inode 里面就可以了。</p>
<p>open 的修改部分： <figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span>((omode &amp; O_NOFOLLOW) == <span class="number">0</span>)&#123;</span><br><span class="line">    <span class="keyword">char</span> s[MAXPATH];</span><br><span class="line">    <span class="keyword">int</span> cnt = <span class="number">0</span>, length;</span><br><span class="line">    <span class="keyword">while</span>(cnt &lt; <span class="number">10</span> &amp;&amp; ip-&gt;type == T_SYMLINK)&#123;</span><br><span class="line">        cnt ++;</span><br><span class="line">        readi(ip, <span class="number">0</span>, (uint64)&amp;length, <span class="number">0</span>, <span class="number">4</span>);</span><br><span class="line">        readi(ip, <span class="number">0</span>, (uint64)s, <span class="number">4</span>, length);</span><br><span class="line">        s[length] = <span class="number">0</span>;</span><br><span class="line">        iunlockput(ip);</span><br><span class="line">        <span class="keyword">if</span>((ip = namei(s)) == <span class="number">0</span>)&#123;</span><br><span class="line">            end_op();</span><br><span class="line">            <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        ilock(ip);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span>(cnt &gt;= <span class="number">10</span> &amp;&amp; ip-&gt;type == T_SYMLINK)&#123;</span><br><span class="line">        iunlockput(ip);</span><br><span class="line">        end_op();</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>sym_link: <figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">int</span></span></span><br><span class="line"><span class="function"><span class="title">len</span><span class="params">(<span class="keyword">char</span> *s)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> cnt;</span><br><span class="line">    <span class="keyword">for</span>(cnt = <span class="number">0</span>; cnt &lt; MAXPATH; cnt ++)&#123;</span><br><span class="line">        <span class="keyword">if</span>(s[cnt] == <span class="number">0</span>) <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> cnt;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function">uint64</span></span><br><span class="line"><span class="function"><span class="title">sys_symlink</span><span class="params">(<span class="keyword">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">char</span> target[MAXPATH], path[MAXPATH];</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">inode</span> *<span class="title">ip</span>;</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span>(argstr(<span class="number">0</span>, target, MAXPATH) &lt; <span class="number">0</span> || argstr(<span class="number">1</span>, path, MAXPATH) &lt; <span class="number">0</span>)</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line"></span><br><span class="line">    begin_op();</span><br><span class="line">    <span class="keyword">if</span>((ip = create(path, T_SYMLINK, <span class="number">0</span>, <span class="number">0</span>)) == <span class="number">0</span>)&#123;</span><br><span class="line">        end_op();</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">int</span> length = len(target);</span><br><span class="line">    writei(ip, <span class="number">0</span>, (uint64)&amp;length, <span class="number">0</span>, <span class="number">4</span>);</span><br><span class="line">    writei(ip, <span class="number">0</span>, (uint64)target, <span class="number">4</span>, length + <span class="number">1</span>);</span><br><span class="line">    iunlockput(ip);</span><br><span class="line">    end_op();</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h1 id="lab-10-mmap">Lab-10 Mmap</h1>
<p>这个实验的难点在于，mmap 要实现成 lazy alloc 的形式，所以要对页表进行大量的操作，然而做到 lab-10 可能前面页表的细节已经完全忘干净了（</p>
<p>不过缺点也在于测试样例过于简单，感觉覆盖的场景非常不完全。</p>
<p>对于这个 lazy alloc 的处理，我选择了一种比较取巧的方式，就是在开始的时候完全按照 lazy alloc 的那个方式来写，在最后判断的时候，多加一个 mmap 的判断：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">void</span></span></span><br><span class="line"><span class="function"><span class="title">mmaplazyalloc</span><span class="params">(<span class="keyword">int</span> va)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">proc</span> *<span class="title">p</span> =</span> myproc();</span><br><span class="line">  <span class="keyword">int</span> found = <span class="number">0</span>, i = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; <span class="number">16</span>; i++) &#123;</span><br><span class="line">    <span class="keyword">if</span> (p-&gt;mmaps[i].used) &#123;</span><br><span class="line">      uint64 start = p-&gt;mmaps[i].addr;</span><br><span class="line">      uint64 end = p-&gt;mmaps[i].addr + p-&gt;mmaps[i].length;</span><br><span class="line">      <span class="keyword">if</span> (va &gt;= start &amp;&amp; va &lt; end) &#123;</span><br><span class="line">        found = <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (found == <span class="number">0</span>)</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">  </span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">file</span> *<span class="title">f</span> =</span> p-&gt;mmaps[i].f;</span><br><span class="line">  <span class="keyword">int</span> offset = p-&gt;mmaps[i].offset;</span><br><span class="line">  uint64 off = offset + va - p-&gt;mmaps[i].addr;</span><br><span class="line"></span><br><span class="line">  begin_op();</span><br><span class="line">  ilock(f-&gt;ip);</span><br><span class="line">  <span class="keyword">if</span> (readi(f-&gt;ip, <span class="number">1</span>, va, off, PGSIZE) &lt; <span class="number">0</span>) &#123;</span><br><span class="line">    panic(<span class="string">&quot;lazyalloc read.&quot;</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  iunlock(f-&gt;ip);</span><br><span class="line">  end_op();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">......</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span>((which_dev = devintr()) != <span class="number">0</span>)&#123;</span><br><span class="line">    <span class="comment">// ok</span></span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (r_scause() == <span class="number">13</span> || r_scause() == <span class="number">15</span>) &#123;</span><br><span class="line">    uint64 va = r_stval();</span><br><span class="line">    va = PGROUNDDOWN(va);</span><br><span class="line">    <span class="keyword">if</span> (va &gt;= p-&gt;sz || va &lt; PGROUNDUP(p-&gt;trapframe-&gt;sp)) &#123;</span><br><span class="line">      p-&gt;killed = <span class="number">1</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (walkaddr(p-&gt;pagetable, va) == <span class="number">0</span>) &#123;</span><br><span class="line">      p-&gt;killed = <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    mmaplazyalloc(va);</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;usertrap(): unexpected scause %p pid=%d\n&quot;</span>, r_scause(), p-&gt;pid);</span><br><span class="line">    <span class="built_in">printf</span>(<span class="string">&quot;            sepc=%p stval=%p\n&quot;</span>, r_sepc(), r_stval());</span><br><span class="line">    p-&gt;killed = <span class="number">1</span>;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<p>另一个比较麻烦的地方就是对 munmap 的处理，因为题目保证了 munmap 要么截断前面，要么截断后面，不会截断中间，所以要对这几种情况进行调整：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br></pre></td><td class="code"><pre><span class="line"><span class="function">uint64</span></span><br><span class="line"><span class="function"><span class="title">sys_mmap</span><span class="params">(<span class="keyword">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  uint64 addr;</span><br><span class="line">  <span class="keyword">int</span> length, prot, flags, fd, offset;</span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">file</span>* <span class="title">f</span>;</span></span><br><span class="line">  <span class="keyword">if</span> (argaddr(<span class="number">0</span>, &amp;addr) &lt; <span class="number">0</span> ||</span><br><span class="line">    argint(<span class="number">1</span>, &amp;length) &lt; <span class="number">0</span> ||</span><br><span class="line">    argint(<span class="number">2</span>, &amp;prot) &lt; <span class="number">0</span> ||</span><br><span class="line">    argint(<span class="number">3</span>, &amp;flags) &lt; <span class="number">0</span> ||</span><br><span class="line">    argfd(<span class="number">4</span>, &amp;fd, &amp;f)  &lt; <span class="number">0</span> ||</span><br><span class="line">    argint(<span class="number">5</span>, &amp;offset) &lt; <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span>((prot &amp; PROT_WRITE) &amp;&amp; !f-&gt;writable &amp;&amp; flags == MAP_SHARED)</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1UL</span>;</span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">proc</span> *<span class="title">p</span> =</span> myproc();</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">16</span>; i ++) &#123;</span><br><span class="line">    <span class="keyword">if</span> (!p-&gt;mmaps[i].used) &#123;</span><br><span class="line">      <span class="class"><span class="keyword">struct</span> <span class="title">vma</span>* <span class="title">v</span> =</span> &amp;p-&gt;mmaps[i];</span><br><span class="line">      v-&gt;addr = p-&gt;sz;</span><br><span class="line">      v-&gt;length = length;</span><br><span class="line">      v-&gt;f = f;</span><br><span class="line">      v-&gt;prot = prot;</span><br><span class="line">      v-&gt;used = <span class="number">1</span>;</span><br><span class="line">      v-&gt;flags = flags;</span><br><span class="line">      v-&gt;offset = offset;</span><br><span class="line">      p-&gt;sz = p-&gt;sz + length;</span><br><span class="line">      filedup(f);</span><br><span class="line">      <span class="keyword">return</span> v-&gt;addr;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function">uint64</span></span><br><span class="line"><span class="function"><span class="title">sys_munmap</span><span class="params">(<span class="keyword">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  uint64 addr;</span><br><span class="line">  <span class="keyword">int</span> length;</span><br><span class="line">  <span class="keyword">int</span> found = <span class="number">0</span>, i = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">if</span> (argaddr(<span class="number">0</span>, &amp;addr) &lt; <span class="number">0</span> ||</span><br><span class="line">    argint(<span class="number">1</span>, &amp;length) &lt; <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">proc</span> *<span class="title">p</span> =</span> myproc();</span><br><span class="line">  <span class="class"><span class="keyword">struct</span> <span class="title">vma</span>* <span class="title">v</span> =</span> <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; <span class="number">16</span>; i++) &#123;</span><br><span class="line">    <span class="keyword">if</span> (p-&gt;mmaps[i].used) &#123;</span><br><span class="line">      uint64 start = p-&gt;mmaps[i].addr;</span><br><span class="line">      uint64 end = p-&gt;mmaps[i].addr + p-&gt;mmaps[i].length;</span><br><span class="line">      <span class="keyword">if</span> (addr &gt;= start &amp;&amp; addr &lt; end) &#123;</span><br><span class="line">        found = <span class="number">1</span>;</span><br><span class="line">        v = &amp;p-&gt;mmaps[i];</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">if</span> (found == <span class="number">0</span>)</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">  </span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">int</span> offset = <span class="number">0</span>; offset &lt; length; offset += PGSIZE) &#123;</span><br><span class="line">    uint64 a = addr + offset;</span><br><span class="line">    <span class="keyword">if</span> (p-&gt;mmaps[i].flags &amp; MAP_SHARED) &#123;</span><br><span class="line">        <span class="keyword">pte_t</span> *pte = walk(p-&gt;pagetable, a, <span class="number">0</span>);</span><br><span class="line">        <span class="keyword">if</span> (pte != <span class="number">0</span> &amp;&amp; (*pte &amp; PTE_V) != <span class="number">0</span>) &#123;</span><br><span class="line">            begin_op();</span><br><span class="line">            ilock(v-&gt;f-&gt;ip);</span><br><span class="line">            writei(v-&gt;f-&gt;ip, <span class="number">1</span>, a, a - v-&gt;addr + v-&gt;offset, PGSIZE);</span><br><span class="line">            iunlock(v-&gt;f-&gt;ip);</span><br><span class="line">            end_op();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    uvmunmap(p-&gt;pagetable, a, <span class="number">1</span>, <span class="number">1</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  </span><br><span class="line">  <span class="keyword">if</span> (addr == v-&gt;addr) &#123;</span><br><span class="line">    <span class="keyword">if</span> (length == v-&gt;length) &#123;</span><br><span class="line">      v-&gt;used = <span class="number">0</span>;</span><br><span class="line">      fileclose(v-&gt;f);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (addr + length &gt; v-&gt;addr + v-&gt;length) &#123;</span><br><span class="line">      panic(<span class="string">&quot;munmap: wrong&quot;</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      v-&gt;addr = addr + length;</span><br><span class="line">      v-&gt;offset = v-&gt;offset + length;</span><br><span class="line">      v-&gt;length -= length;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (addr + length == v-&gt;addr + v-&gt;length) &#123;</span><br><span class="line">      v-&gt;length = addr - v-&gt;addr;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      panic(<span class="string">&quot;munmap: wrong&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>需要注意的是，我们在 writei 的时候，截断的 offset 要补入 p-&gt;mmaps[i] 的 offset 中，这样才能找到正确的 offset。</p>
<h1 id="lab-11-networking">Lab-11 Networking</h1>
<p>最后一个实验了，非常简单，就是让我们实现 e1000_transmit 和 e1000_recv 这两个函数。看起来仿佛非常复杂，实际上按照 hint 模拟就好了。</p>
<p>但是有个地方需要注意，在 hint 中， e1000_recv 实现方式如下：</p>
<blockquote>
<p>Some hints for implementing e1000_recv: First ask the E1000 for the ring index at which the next waiting received packet (if any) is located, by fetching the E1000_RDT control register and adding one modulo RX_RING_SIZE. Then check if a new packet is available by checking for the E1000_RXD_STAT_DD bit in the status portion of the descriptor. If not, stop. Otherwise, update the mbuf's m-&gt;len to the length reported in the descriptor. Deliver the mbuf to the network stack using net_rx(). Then allocate a new mbuf using mbufalloc() to replace the one just given to net_rx(). Program its data pointer (m-&gt;head) into the descriptor. Clear the descriptor's status bits to zero. Finally, update the E1000_RDT register to be the index of the last ring descriptor processed. e1000_init() initializes the RX ring with mbufs, and you'll want to look at how it does that and perhaps borrow code. At some point the total number of packets that have ever arrived will exceed the ring size (16); make sure your code can handle that.</p>
</blockquote>
<p>但是在实际实现中，net_rx要先release锁之后才能去运行，不然就会panic：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">static</span> <span class="keyword">void</span></span></span><br><span class="line"><span class="function"><span class="title">e1000_recv</span><span class="params">(<span class="keyword">void</span>)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="keyword">while</span> (<span class="number">1</span>) &#123;</span><br><span class="line">    acquire(&amp;e1000_lock);</span><br><span class="line">    uint32 idx = (regs[E1000_RDT] + <span class="number">1</span>) % RX_RING_SIZE;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">rx_desc</span> *<span class="title">desc</span> =</span> &amp;rx_ring[idx];</span><br><span class="line">    <span class="keyword">if</span> (!(desc-&gt;status &amp; E1000_RXD_STAT_DD)) &#123;</span><br><span class="line">        release(&amp;e1000_lock);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    rx_mbufs[idx]-&gt;len = desc-&gt;length;</span><br><span class="line">    <span class="class"><span class="keyword">struct</span> <span class="title">mbuf</span> *<span class="title">m</span> =</span> rx_mbufs[idx];</span><br><span class="line">    rx_mbufs[idx] = mbufalloc(<span class="number">0</span>);</span><br><span class="line">    desc-&gt;addr = (uint64) rx_mbufs[idx]-&gt;head;</span><br><span class="line">    desc-&gt;status = <span class="number">0</span>;</span><br><span class="line">    regs[E1000_RDT] = idx;</span><br><span class="line">    release(&amp;e1000_lock);</span><br><span class="line">    net_rx(m);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/OS/" rel="tag"># OS</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/03/09/gnn-for-source-code-modeling-3/" rel="prev" title="GNN for Source Code Modeling（三）">
      <i class="fa fa-chevron-left"></i> GNN for Source Code Modeling（三）
    </a></div>
      <div class="post-nav-item"></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#lab-1-utilities"><span class="nav-number">1.</span> <span class="nav-text">Lab-1 Utilities</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#sleep-pingpong"><span class="nav-number">1.1.</span> <span class="nav-text">sleep &amp; pingpong</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#primes"><span class="nav-number">1.2.</span> <span class="nav-text">primes</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#find"><span class="nav-number">1.3.</span> <span class="nav-text">find</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#xargs"><span class="nav-number">1.4.</span> <span class="nav-text">xargs</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#lab-2-system-calls"><span class="nav-number">2.</span> <span class="nav-text">Lab-2 System calls</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#lab-3-page-tables"><span class="nav-number">3.</span> <span class="nav-text">Lab-3 Page tables</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#print-a-page-table"><span class="nav-number">3.1.</span> <span class="nav-text">Print a page table</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#a-kernel-page-table-per-process"><span class="nav-number">3.2.</span> <span class="nav-text">A kernel page table per process</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#simplify-copyincopyinstr"><span class="nav-number">3.3.</span> <span class="nav-text">Simplify copyin&#x2F;copyinstr</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#lab-4-traps"><span class="nav-number">4.</span> <span class="nav-text">Lab-4 Traps</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#risc-v-assembly"><span class="nav-number">4.1.</span> <span class="nav-text">RISC-V assembly</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#backtrace"><span class="nav-number">4.2.</span> <span class="nav-text">Backtrace</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#alarm"><span class="nav-number">4.3.</span> <span class="nav-text">Alarm</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#lab-5-lazy-page-allocation"><span class="nav-number">5.</span> <span class="nav-text">Lab-5 Lazy Page Allocation</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#eliminate-allocation-from-sbrk"><span class="nav-number">5.1.</span> <span class="nav-text">Eliminate allocation from sbrk()</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#lazy-allocation"><span class="nav-number">5.2.</span> <span class="nav-text">Lazy allocation</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#lazytests-and-usertests"><span class="nav-number">5.3.</span> <span class="nav-text">Lazytests and Usertests</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#lab-6-copy-on-write-fork-for-xv6"><span class="nav-number">6.</span> <span class="nav-text">Lab-6 Copy-on-Write Fork for xv6</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#lab-7-multithreading"><span class="nav-number">7.</span> <span class="nav-text">Lab-7 Multithreading</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#uthread-switching-between-threads"><span class="nav-number">7.1.</span> <span class="nav-text">Uthread: switching between threads</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#using-threads"><span class="nav-number">7.2.</span> <span class="nav-text">Using threads</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#barrier"><span class="nav-number">7.3.</span> <span class="nav-text">Barrier</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#lab-8-locks"><span class="nav-number">8.</span> <span class="nav-text">Lab-8 Locks</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#lab-9-file-system"><span class="nav-number">9.</span> <span class="nav-text">Lab-9 File System</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#large-files"><span class="nav-number">9.1.</span> <span class="nav-text">Large files</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#symbolic-links"><span class="nav-number">9.2.</span> <span class="nav-text">Symbolic links</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#lab-10-mmap"><span class="nav-number">10.</span> <span class="nav-text">Lab-10 Mmap</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#lab-11-networking"><span class="nav-number">11.</span> <span class="nav-text">Lab-11 Networking</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Reku</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">78</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
        <span class="site-state-item-count">8</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">96</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/wyc-ruiker" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;wyc-ruiker" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://www.zhihu.com/people/reku1997" title="ZhiHu → https:&#x2F;&#x2F;www.zhihu.com&#x2F;people&#x2F;reku1997" rel="noopener" target="_blank"><i class="fa fa-fw fa-quora"></i>ZhiHu</a>
      </span>
      <span class="links-of-author-item">
        <a href="http://codeforces.com/profile/reku" title="CodeForces → http:&#x2F;&#x2F;codeforces.com&#x2F;profile&#x2F;reku" rel="noopener" target="_blank"><i class="fa fa-fw fa-code"></i>CodeForces</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://www.linkedin.cn/injobs/in/reku" title="Linkedin → https:&#x2F;&#x2F;www.linkedin.cn&#x2F;injobs&#x2F;in&#x2F;reku" rel="noopener" target="_blank"><i class="fa fa-fw fa-linkedin"></i>Linkedin</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://gitee.com/reku1997" title="Gitee → https:&#x2F;&#x2F;gitee.com&#x2F;reku1997" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>Gitee</a>
      </span>
      <span class="links-of-author-item">
        <a href="/./atom.xml" title="RSS → .&#x2F;atom.xml"><i class="fa fa-fw fa-rss"></i>RSS</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2016 – 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Reku</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a>
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="Total Visitors">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="Total Views">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="//cdn.jsdelivr.net/npm/algoliasearch@4/dist/algoliasearch-lite.umd.js"></script>
<script src="//cdn.jsdelivr.net/npm/instantsearch.js@4/dist/instantsearch.production.min.js"></script>
<script src="/js/algolia-search.js"></script>














  

  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'MWLzM550UOu69h3dgvbbLSsF-gzGzoHsz',
      appKey     : 'gkKnwm9FK0cu3ysJbcggsCDz',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : true,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
